import { createRouter, createWebHistory } from 'vue-router'
import { useUserStore } from '@/stores/user'
import { useAppStore } from '@/stores/app'
import NProgress from 'nprogress'
import 'nprogress/nprogress.css'

// 配置NProgress
NProgress.configure({ 
  showSpinner: false,
  minimum: 0.2,
  easing: 'ease',
  speed: 500
})

// 路由配置
const routes = [
  {
    path: '/',
    name: 'Home',
    component: () => import('@/views/Home/index.vue'),
    meta: {
      title: '首页',
      keepAlive: true,
      showTabBar: true
    }
  },
  {
    path: '/login',
    name: 'Login',
    component: () => import('@/views/Auth/Login.vue'),
    meta: {
      title: '登录',
      hideNavBar: true
    }
  },
  {
    path: '/register',
    name: 'Register',
    component: () => import('@/views/Auth/Register.vue'),
    meta: {
      title: '注册',
      hideNavBar: true
    }
  },
  {
    path: '/forgot-password',
    name: 'ForgotPassword',
    component: () => import('@/views/Auth/ForgotPassword.vue'),
    meta: {
      title: '忘记密码',
      hideNavBar: true
    }
  },
  {
    path: '/courses',
    name: 'Courses',
    component: () => import('@/views/Course/index.vue'),
    meta: {
      title: '课程',
      keepAlive: true,
      showTabBar: true
    }
  },
  {
    path: '/courses/:id',
    name: 'CourseDetail',
    component: () => import('@/views/Course/Detail.vue'),
    meta: {
      title: '课程详情'
    }
  },
  {
    path: '/courses/:id/learn',
    name: 'CourseLearn',
    component: () => import('@/views/Course/Learn.vue'),
    meta: {
      title: '学习课程',
      requiresAuth: true,
      hideTabBar: true
    }
  },
  {
    path: '/exams',
    name: 'Exams',
    component: () => import('@/views/Exam/index.vue'),
    meta: {
      title: '考试',
      keepAlive: true,
      showTabBar: true
    }
  },
  {
    path: '/exams/:id',
    name: 'ExamDetail',
    component: () => import('@/views/Exam/Detail.vue'),
    meta: {
      title: '考试详情'
    }
  },
  {
    path: '/exams/:id/take',
    name: 'ExamTake',
    component: () => import('@/views/Exam/Take.vue'),
    meta: {
      title: '参加考试',
      requiresAuth: true,
      hideTabBar: true,
      preventBack: true
    }
  },
  {
    path: '/exams/:id/result',
    name: 'ExamResult',
    component: () => import('@/views/Exam/Result.vue'),
    meta: {
      title: '考试结果',
      requiresAuth: true
    }
  },
  {
    path: '/profile',
    name: 'Profile',
    component: () => import('@/views/Profile/index.vue'),
    meta: {
      title: '我的',
      requiresAuth: true,
      keepAlive: true,
      showTabBar: true
    }
  },
  {
    path: '/profile/edit',
    name: 'ProfileEdit',
    component: () => import('@/views/Profile/Edit.vue'),
    meta: {
      title: '编辑资料',
      requiresAuth: true
    }
  },
  {
    path: '/profile/settings',
    name: 'Settings',
    component: () => import('@/views/Profile/Settings.vue'),
    meta: {
      title: '设置',
      requiresAuth: true
    }
  },
  {
    path: '/profile/my-courses',
    name: 'MyCourses',
    component: () => import('@/views/Profile/MyCourses.vue'),
    meta: {
      title: '我的课程',
      requiresAuth: true
    }
  },
  {
    path: '/profile/my-exams',
    name: 'MyExams',
    component: () => import('@/views/Profile/MyExams.vue'),
    meta: {
      title: '我的考试',
      requiresAuth: true
    }
  },
  {
    path: '/search',
    name: 'Search',
    component: () => import('@/views/Search/index.vue'),
    meta: {
      title: '搜索'
    }
  },
  {
    path: '/notifications',
    name: 'Notifications',
    component: () => import('@/views/Notification/index.vue'),
    meta: {
      title: '消息通知',
      requiresAuth: true
    }
  },
  {
    path: '/about',
    name: 'About',
    component: () => import('@/views/About/index.vue'),
    meta: {
      title: '关于我们'
    }
  },
  {
    path: '/help',
    name: 'Help',
    component: () => import('@/views/Help/index.vue'),
    meta: {
      title: '帮助中心'
    }
  },
  {
    path: '/privacy',
    name: 'Privacy',
    component: () => import('@/views/Legal/Privacy.vue'),
    meta: {
      title: '隐私政策'
    }
  },
  {
    path: '/terms',
    name: 'Terms',
    component: () => import('@/views/Legal/Terms.vue'),
    meta: {
      title: '服务条款'
    }
  },
  {
    path: '/error',
    name: 'Error',
    component: () => import('@/views/Error/index.vue'),
    meta: {
      title: '错误页面'
    }
  },
  {
    path: '/offline',
    name: 'Offline',
    component: () => import('@/views/Offline/index.vue'),
    meta: {
      title: '离线页面'
    }
  },
  {
    path: '/:pathMatch(.*)*',
    name: 'NotFound',
    component: () => import('@/views/Error/NotFound.vue'),
    meta: {
      title: '页面不存在'
    }
  }
]

// 创建路由实例
const router = createRouter({
  history: createWebHistory(import.meta.env.BASE_URL),
  routes,
  scrollBehavior(to, from, savedPosition) {
    if (savedPosition) {
      return savedPosition
    } else {
      return { top: 0 }
    }
  }
})

// 路由守卫
router.beforeEach(async (to, from, next) => {
  // 开始进度条
  NProgress.start()
  
  const userStore = useUserStore()
  const appStore = useAppStore()
  
  // 设置页面标题
  if (to.meta.title) {
    document.title = `${to.meta.title} - RX在线教育平台`
  }
  
  // 检查网络状态
  if (!navigator.onLine && to.name !== 'Offline') {
    next({ name: 'Offline' })
    return
  }
  
  // 检查登录状态
  if (to.meta.requiresAuth) {
    if (!userStore.isLoggedIn) {
      // 未登录，跳转到登录页
      next({
        name: 'Login',
        query: { redirect: to.fullPath }
      })
      return
    }
    
    // 检查用户权限
    if (to.meta.roles && !to.meta.roles.includes(userStore.user.role)) {
      // 权限不足
      next({ name: 'Error', query: { code: '403' } })
      return
    }
  }
  
  // 如果已登录用户访问登录页，重定向到首页
  if (userStore.isLoggedIn && ['Login', 'Register'].includes(to.name)) {
    next({ name: 'Home' })
    return
  }
  
  // 防止返回（考试页面）
  if (to.meta.preventBack && from.name) {
    // 可以在这里添加确认对话框
    const confirmed = await new Promise((resolve) => {
      showConfirmDialog({
        title: '确认离开',
        message: '离开此页面将丢失当前进度，确定要离开吗？'
      }).then(() => resolve(true)).catch(() => resolve(false))
    })
    
    if (!confirmed) {
      next(false)
      return
    }
  }
  
  // 更新keep-alive组件列表
  if (to.meta.keepAlive) {
    appStore.addKeepAliveComponent(to.name)
  } else {
    appStore.removeKeepAliveComponent(to.name)
  }
  
  next()
})

router.afterEach((to, from) => {
  // 结束进度条
  NProgress.done()
  
  // 页面访问统计
  if (import.meta.env.PROD) {
    // 发送页面访问统计
    // analytics.trackPageView(to.fullPath)
  }
  
  // 设置页面过渡动画
  const toDepth = to.path.split('/').length
  const fromDepth = from.path.split('/').length
  
  if (toDepth > fromDepth) {
    to.meta.transition = 'slide-left'
  } else if (toDepth < fromDepth) {
    to.meta.transition = 'slide-right'
  } else {
    to.meta.transition = 'fade'
  }
})

// 路由错误处理
router.onError((error) => {
  console.error('路由错误:', error)
  NProgress.done()
  
  // 跳转到错误页面
  router.push({ name: 'Error', query: { message: error.message } })
})

export default router